// ItgImage.cpp: implementation of the McItgImage class.
//
//////////////////////////////////////////////////////////////////////
#include "ItgImage.h"
#include "fstream"

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

McItgImage::McItgImage()
{
	m_w = m_h = 0;
}

McItgImage::~McItgImage()
{
}

//
// return:  0 if success
//          otherwise failed
//
int McItgImage::Prepare(const Raster<uchar> &srcimg, bool bexpend_one)
{
	if (bexpend_one)
	{
		Raster<uchar>	ras_temp;
		int				i,j;

		ras_temp.SetDimension(srcimg.rows()+1, srcimg.cols()+1);
		for (j=0; j<ras_temp.rows(); j++)
			ras_temp(j, 0) = 0;
		for (i=0; i<ras_temp.cols(); i++)
			ras_temp(0, i) = 0;
		for (j=0; j<srcimg.rows(); j++)
			for (i=0; i<srcimg.cols(); i++)
				ras_temp(j+1, i+1) = srcimg.Data(j,i);

		return Prepare(ras_temp, false);
	}
	
	ras_sum_image.SetDimension(srcimg.rows(), srcimg.cols());
	ras_sq_image.SetDimension(srcimg.rows(), srcimg.cols());

	int w = m_w = srcimg.Width();
	int h = m_h = srcimg.Height();

	unsigned v = srcimg.Data(0,0);
	ras_sum_image(0,0) = v;
	ras_sq_image(0,0) = v * v;
	int x, y;
	for (x = 1; x < w; x++)
	{
		v = srcimg.Data(0, x);
		ras_sum_image(0, x) = ras_sum_image(0, x-1) + v;
		ras_sq_image(0, x) = ras_sq_image(0, x-1) + v * v;
	}

	for (y = 1; y < h; y++)
	{
		v = srcimg.Data(y, 0);
		ras_sum_image(y, 0) = ras_sum_image(y-1, 0) + v;
		ras_sq_image(y, 0) = ras_sq_image(y-1, 0) + v * v;
	}
	
	for (y = 1; y < h; y++)
	{
		for (x = 1; x < w; x++)
		{
			v = srcimg.Data(y, x);
			ras_sum_image(y, x) = ras_sum_image(y-1, x) + ras_sum_image(y, x-1) - ras_sum_image(y-1, x-1) + v;
			ras_sq_image(y, x) = ras_sq_image(y-1, x) + ras_sq_image(y, x-1) - ras_sq_image(y-1, x-1) + v * v;
		}
	}

	m_std = CalcuSTD(irmm_Rect(0,0,w,h) );

	return 0;
}

